package com.yzz.hzraisedust.hzraseidust.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.Fragment;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;
import com.yzz.hzraisedust.hzraseidust.R;
import com.yzz.hzraisedust.hzraseidust.modelbean.MapInfoBean;
import com.yzz.hzraisedust.hzraseidust.modelbean.MapItemBean;
import com.yzz.hzraisedust.hzraseidust.util.Constant;

import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link MapInfoFragment} factory method to
 * create an instance of this fragment.
 */
public class MapInfoFragment extends Fragment implements Response.Listener<MapInfoBean>,FilterDropDownList.CallBack ,LocationManager.LCallBack{
    public static final String TAG = MapInfoFragment.class.getName();

    private MapView mMapView;
    private BaiduMap mBaidumap;
    private static MapInfoFragment Instance;
    private MapInfoControl mMapInfoControl;
    private com.yzz.hzraisedust.hzraseidust.main.DropDownList mDropDownList;
    private FilterDropDownList mFileterDropDownList;
    private LocationManager mLocation;
    private ImageView mLocationImageView;
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    public MapInfoFragment() {
        mMapInfoControl = new MapInfoControl(getActivity());

        mMapInfoControl.setListener(this);
    }
    public static MapInfoFragment getInstance(){
        if(Instance == null){
            Instance = new MapInfoFragment();
        }
        return Instance;
    }

    private void initMap(){
        //隐藏百度地图logo
        mMapView.getChildAt(1).setVisibility(View.GONE);
        //隐藏缩放+-
        mMapView.getChildAt(2).setVisibility(View.GONE);
        //隐藏标尺
        mMapView.getChildAt(3).setVisibility(View.GONE);
        mBaidumap = mMapView.getMap();
        mBaidumap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mBaidumap.hideInfoWindow();
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
        mBaidumap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener(){
            @Override
            public boolean onMarkerClick(Marker marker) {
                Bundle bundle = marker.getExtraInfo();
                MapItemBean item = (MapItemBean) bundle.getSerializable(Constant.ITEM_KEY);
                if(item == null) return false;
                //创建InfoWindow展示的view
                showPopItem(item);
                return true;
            }


        });

    }
    private void showPopItem(MapItemBean item) {
        getPopItem(item);
        //定义用于显示该InfoWindow的坐标点
        LatLng pt = new LatLng(item.getLat(), item.getLng());
        //设置当前为地图中心点
        setMapCenter(pt,mBaidumap.getMapStatus().zoom);
        if(mView.getParent() !=null){

        }
        //创建InfoWindow , 传入 view， 地理坐标， y 轴偏移量
        InfoWindow mInfoWindow = new InfoWindow(mView, pt, -47);

        //显示InfoWindow
        mBaidumap.showInfoWindow(mInfoWindow);
    }
    private View mView;

    @Override
    public void filterArea(String areaName, String airQualityContidion) {
        //筛选
        mMapInfoControl.searAreaAndQualityItems(areaName,airQualityContidion);
        // 更新显示
        loadProjectMapInfo();
    }
    @Override
    public void changeLocation(BDLocation location) {
        LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
        setMapCenter(latLng,15);
        mLocation.stopLocation();
        ((BaseActivity)getActivity()).closeLoginingDlg();
    }

    class HoldView{
        TextView projectNameTextView;
        TextView projectAdressTextView;
        TextView projectPmTextView;
        TextView projectPmValueTextView;
        TextView projectUpdataTimeTextView;
        TextView projectDetailTextView;
    }
    private void getPopItem(final MapItemBean itemBean){
        HoldView holdView = null;
            mView = LayoutInflater.from(MapInfoFragment.this.getActivity()).inflate(R.layout.projectitem_detail_layout, null, false);
            holdView = new HoldView();
            holdView.projectNameTextView = mView.findViewById(R.id.project_name_textview);
            holdView.projectAdressTextView= mView.findViewById(R.id.project_address_textview);
            holdView.projectPmTextView = mView.findViewById(R.id.project_pminfo_textview);
            holdView.projectPmValueTextView = mView.findViewById(R.id.project_pm10_textview);
            holdView.projectUpdataTimeTextView = mView.findViewById(R.id.project_pm10_updatatime_textview);
            holdView.projectDetailTextView = mView.findViewById(R.id.project_getdetail_info_textview);
            mView.setTag(holdView);

        holdView.projectNameTextView.setText("监测点名称： "+itemBean.getName());
        holdView.projectAdressTextView.setText("监测点地址："+itemBean.getProjectAddress());
        holdView.projectPmValueTextView.setText("PM值   ：Pm10:"+itemBean.getPm10()+"; Pm2.5:"+itemBean.getPm2_5());
       holdView.projectUpdataTimeTextView.setText("更新时间:"+itemBean.getUpdatetime());
        holdView.projectPmTextView.setText("空气质量等级："+itemBean.getPmDescribe());
        holdView.projectDetailTextView.setTag(itemBean);
        holdView.projectDetailTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MapItemBean item = (MapItemBean)view.getTag();
                if(item == null) return;
                if(item.isState() == 0){
                    Toast.makeText(MapInfoFragment.this.getActivity(),"设备已离线",Toast.LENGTH_LONG).show();
                   // mBaidumap.hideInfoWindow();
                    //return;
                }
                getDetailItemInfo(item);
            }
        });
    }

    private void setMapCenter(LatLng center,float lever){
        MapStatus status = new MapStatus.Builder().target(center)
                .zoom(lever).build();
        MapStatusUpdate update = MapStatusUpdateFactory.newMapStatus(status);
        mBaidumap.setMapStatus(update);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onStart() {
        super.onStart();
        //获取全部设备信息
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       View view= inflater.inflate(R.layout.fragment_map_info, container, false);
       mMapView = view.findViewById(R.id.bmapView);
        mLocationImageView = view.findViewById(R.id.location_self_imageView);
        mLocationImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mLocation!=null){
                    ((BaseActivity)getActivity()).showLoginingDlg();
                    mLocation.startLocation();
                }
            }
        });
       View layout = view.findViewById(R.id.dropdown_layout);

        mDropDownList = new com.yzz.hzraisedust.hzraseidust.main.DropDownList(getActivity(), layout, new DropDownList.CallBack() {
            @Override
            public void searchItem(MapItemBean itemBean) {
                LatLng latLng = new LatLng(itemBean.getLat(), itemBean.getLng());
                setMapCenter(latLng,20);
                showPopItem(itemBean);
            }
        });
        TextView filter = view.findViewById(R.id.filter_text);
        mFileterDropDownList = new FilterDropDownList(getActivity(),filter,this);

        initMap();
        mMapInfoControl.setContext(getActivity());
        ((BaseActivity)getActivity()).showLoginingDlg();
        mMapInfoControl.requstData();
        return view;
    }



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();

    }

    @Override
    public void onResponse(MapInfoBean mapInfoBean) {
        ((InfoActivity)getActivity()).closeLoginingDlg();
        if(mapInfoBean!=null){
            if(mapInfoBean.isSuccess()){
                mDropDownList.setItems(mapInfoBean.getRows());
               mFileterDropDownList.setItems(mMapInfoControl.getmAreaConditions(),mMapInfoControl.getmAirQualityConditions());
               updateMapInfo(mapInfoBean);
            }else {
                Toast.makeText(MapInfoFragment.this.getActivity(),mapInfoBean.getMessage(),Toast.LENGTH_LONG).show();
            }
        }
        mLocation = new LocationManager(MapInfoFragment.this.getActivity(),this);
    }

    private  void getDetailItemInfo(MapItemBean mapItemBean){
    //    Intent intent = new Intent(getActivity(), PmDetailActivity.class);
        Intent intent = new Intent(getActivity(), DeviceDetailActivity.class);

        Bundle bundle = new Bundle();
        bundle.putSerializable(Constant.MAP_ITEM_BEAN,mapItemBean);
        intent.putExtras(bundle);
        //intent.putExtra(Constant.SN_UPPER_KEY,mapItemBean.getSN());
        startActivity(intent);
    }

    private void loadProjectTextInfo(LatLng latLng,String text){
        //构建文字Option对象，用于在地图上添加文字

        OverlayOptions textOption = new TextOptions()
                .bgColor(0xAAFFFF00)
                .fontSize(24)
                .fontColor(0xFFFF00FF).zIndex(50)
                .text(text).rotate(0).position(latLng);
        //在地图上添加该文字对象并显示
       // mBaidumap.addOverlay(textOption);
    }
    private void loadProjectMapInfo(){
        LatLng center = new LatLng(mMapInfoControl.getMapInfoBean().getLat(),mMapInfoControl.getMapInfoBean().getLng());
        setMapCenter(center,8);
        mBaidumap.clear();
        List<MapItemBean> beans = mMapInfoControl.getmShowMapInfoBean().getRows();

        for(MapItemBean item : beans) {
            if(item.getPmDescribe() == null){
                item.concute();
            }
            //定义Maker坐标点
            LatLng point = new LatLng(item.getLat(), item.getLng());
            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(item.getBackGroudId());;
            //构建MarkerOption，用于在地图上添加Marker
            OverlayOptions option = new MarkerOptions()
                                .position(point)
                                .icon(bitmap);

            //在地图上添加Marker，并显示
           Marker marker = (Marker) mBaidumap.addOverlay(option);
           Bundle bundle = new Bundle();
            //info必须实现序列化接口
            bundle.putSerializable(Constant.ITEM_KEY, item);
            marker.setExtraInfo(bundle);
            loadProjectTextInfo(point,item.getName());
        }
    }

    private void updateMapInfo(MapInfoBean mapInfoBean) {
        LatLng center = new LatLng(mapInfoBean.getLat(),mapInfoBean.getLng());
        //设置地图中心点
        setMapCenter(center,8);
        //添加标注
        loadProjectMapInfo();
    }

    public void closeDialog(){
        ((BaseActivity)getActivity()).closeLoginingDlg();
    }

}
